<?php
class Controller_Storage_OtherIO extends Controller_Abstract
{
	function actionInCreate()
	{
		$this->_view['title'] = '新建其他入库单';
		$user = User::getOnDutyUser();
		$this->_view['user'] = $user;
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		if ($this->_context->isPOST())
		{
			$check_in_db = Other_IO::find('id=?', $_POST['id'])->asArray()->getOne();
			if ($check_in_db)
			{
				$item = Other_IO_Item::find('other_io_item.other_io_id=?', $_POST['id'])
					->joinLeft('product_basic', 'name, number', 'product_basic.id=other_io_item.product_basic_id')
					->asArray()->getAll();
				$this->_view['warehouse_id'] = $check_in_db['warehouse_id'];
				$this->_view['discount'] = $_POST['discount'];
				$this->_view['item'] = $item;
			}
		}
	}
	
	function actionInCreateSave()
	{
		$this->_view['title'] = '新建其他入库单（保存）';
		if ($this->_context->isPOST())
		{
			$key_arr = array();
			$item_arr =array();
			foreach ($_POST as $key => $value)
			{
				if (substr($key,0,11) == 'product_id_')
				{
					$key_arr[] = substr($key,11,strlen($key)-11);
				}
			}
			foreach ($key_arr as $k)
			{
				$temp = array();
				$temp['product_basic_id'] = $_POST['product_id_'.$k];
				$temp['quantity'] = abs(intval($_POST['quantity_'.$k]));
				$temp['cost_price'] = $_POST['cost_price_'.$k];
				$item_arr[$k] = $temp;
			}
			$other_io = array(
					'user_id' => $_POST['user_id'],
					'notes' => trim($_POST['notes']),
					'warehouse_id' => $_POST['warehouse_id'],
					'item' => $item_arr
			);
			$result = Other_IO::createOtherIn($other_io);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('保存成功', '正在返回..', url('Storage::OtherIO/InList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('保存失败', '不能生成入库单编号', url('Storage::OtherIO/InCreate'), FAILURE);
			}
		}
	}
	
	function actionInEdit()
	{
		$this->_view['title'] = '其他入库单编辑';
		$id = $_GET['id'];
		if ($id)
		{
			$other_io = Other_IO::find('other_io.id=? and type=?', $id, Q::ini('custom_flag/other_io_type/in/value'))->asArray()->getOne();
			$item = Other_IO_Item::find('other_io_item.other_io_id=?', $id)
			->joinLeft('product_basic', 'name as product_name, number as product_number', 'product_basic.id=other_io_item.product_basic_id')
			->asArray()->getAll();
			$this->_view['other_io'] = $other_io;
			$this->_view['item'] = $item;
			$user = User::getOnDutyUser();
			$this->_view['user'] = $user;
			$warehouse = Warehouse::find()->asArray()->getAll();
			$this->_view['warehouse'] = $warehouse;
		}
	}
	
	function actionInEditSave()
	{
		$this->_view['title'] = '其他入库单编辑（保存）';
		if ($this->_context->isPOST())
		{
			$key_arr = array();
			$item_arr =array();
			foreach ($_POST as $key => $value)
			{
				if (substr($key,0,11) == 'product_id_')
				{
					$key_arr[] = substr($key,11,strlen($key)-11);
				}
			}
			foreach ($key_arr as $k)
			{
				$temp = array();
				$temp['product_basic_id'] = $_POST['product_id_'.$k];
				$temp['quantity'] = abs(intval($_POST['quantity_'.$k]));
				$temp['cost_price'] = $_POST['cost_price_'.$k];
				$item_arr[$k] = $temp;
			}
			$other_io = array(
					'id' => $_POST['other_io_id'],
					'user_id' => $_POST['user_id'],
					'warehouse_id' => $_POST['warehouse_id'],
					'notes' => trim($_POST['notes']),
					'item' => $item_arr
			);
			$result = Other_IO::editOtherIn($other_io);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('保存成功', '正在返回..', url('Storage::OtherIO/InList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('保存失败', $result['message'], $_POST['history'], FAILURE);
			}
		}
	}
	
	function actionInList()
	{
		$this->_view['title'] = '其他入库单列表';
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['type'] = Q::ini('custom_flag/other_io_type/in/value');
		$result = Other_IO::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$other_io = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::OtherIO/InList', $url_arr));
			$this->_view['other_io'] = $other_io;
			$this->_view['page'] = $page->getPage();;
		}
	}
	
	function actionInStorageAudit()
	{
		$this->_view['title'] = '其他入库单仓库审核';
		if ($_GET['id'])
		{
			$result = Other_IO::InStorageAudit($_GET['id']);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('审核成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('审核失败', $result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}

	function actionOutStorageAudit()
	{
		$this->_view['title'] = '其他出库单仓库审核';
		if ($_GET['id'])
		{
			$result = Other_IO::OutStorageAudit($_GET['id']);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('审核成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('审核失败', $result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}
	
	function actionDetail()
	{
		$this->_view['title'] = '其他出入库产品信息详细';
		$id = $_GET['id'];
		if ($id)
		{
			$other_io = Other_IO::find('other_io.id=?', $id)
				->joinLeft('user', 'name as user_name', 'user.id=other_io.user_id')
				->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=other_io.warehouse_id')
				->asArray()->getOne();
			$item = Other_IO_Item::find('other_io_item.other_io_id=?', $id)
				->joinLeft('product_basic', 'name, number', 'product_basic.id=other_io_item.product_basic_id')
				->asArray()->getAll();
			$this->_view['other_io'] = $other_io;
			$this->_view['item'] = $item;
		}
	}
	
	function actionOutCreate()
	{
		$this->_view['title'] = '新建其他出库单';
		$user = User::getOnDutyUser();
		$this->_view['user'] = $user;
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
	}
	
	function actionOutCreateSave()
	{
		$this->_view['title'] = '新建其他出库单（保存）';
		if ($this->_context->isPOST())
		{
			if (empty($_POST['product_data']))
			{
				return $this->_redirectMessage('保存失败', '请填写出库产品信息', $_SERVER['HTTP_REFERER'], FAILURE);
			}
			else
			{
				$product_data = Q::normalize($_POST['product_data'], "\n");
				$item = $message = array();
				foreach ($product_data as $pd)
				{
					$temp = Q::normalize($pd, ',');
					$check_in_db = Product_Basic::find('number=?', $temp[0])->asArray()->getOne();
					if ($check_in_db)
					{
						$warehouse = Product_Warehouse::find('product_basic_id=? and warehouse_id=?', $check_in_db['id'],$_POST['warehouse_id'])->asArray()->getOne();
						if(!$warehouse)
						{
							$message[$temp[0]] = $check_in_db['number'] . '仓库中不存在该产品';
						}
						else
						{
							if (array_key_exists($temp[0], $item))
							{
								$item[$temp[0]]['quantity'] += $temp[1];
							}
							else
							{
								$item[$temp[0]]['product_basic_id'] = $check_in_db['id'];
								$item[$temp[0]]['available_quantity'] = $warehouse['available_quantity'];
								$item[$temp[0]]['quantity'] = $temp[1];
								$item[$temp[0]]['cost_price'] = 0;
							}
						}
					}
					else
					{
						$message[$temp[0]] = $temp[0] . '不存在该产品';
					}
				}
				foreach ($item as $k => $i)
				{
					if ($i['quantity'] > $i['available_quantity'])
					{
						$message[$k] = $k . '可用库存不足，需要出库'.$i['quantity'].',系统剩'.$i['available_quantity'];
					}
					if ($i['quantity'] < 0)
					{
						$message[$k] = $k . '出库产品不能为负数';
					}
				}
				if ($message)
				{
					return $this->_redirectMessage('保存失败', implode(chr(13), $message), $_SERVER['HTTP_REFERER'], FAILURE);
				}
				else
				{
					$other_out = array(
						'user_id' => $_POST['user_id'],
						'warehouse_id' => $_POST['warehouse_id'],
						'notes' => trim($_POST['notes']),
						'item' => $item
					);
					$result = Other_IO::createOtherOut($other_out);
					if ($result['ack'] == SUCCESS)
					{
						return $this->_redirectMessage('保存成功', '正在返回...', url('Storage::OtherIO/OutList'), $result['ack']);
					}
					else
					{
						return $this->_redirectMessage('部分保存失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
					}
				}
			}
		}
		else
		{
			return $this->_redirectMessage('提交方式有误', '正在返回...', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionCheckAvailableQuantity()
	{
		$this->_view['title'] = '检查产品和可用库存';
		$warehouse_id = $_REQUEST['warehouse_id'];
		$product_data = Q::normalize(urldecode($_REQUEST['product_data']), "\n");
		$product = $message = array();
		foreach ($product_data as $pd)		
		{
			$temp = Q::normalize($pd, ',');
			$product_in_db = Product_Basic::find('number=?', $temp[0])->asArray()->getOne();
			if ($product_in_db)
			{
				$warehouse = Product_Warehouse::find('product_basic_id=? and warehouse_id=?', $product_in_db['id'], $warehouse_id)->asArray()->getOne();
				if (!$warehouse)
				{
					$message[$temp[0]][] = '仓库中不存在该产品';
				}
				else
				{
					if (! array_key_exists($temp[0], $product))
					{
						$product[$temp[0]]['id'] = $warehouse['id'];
						$product[$temp[0]]['available_quantity'] = $warehouse['available_quantity'];
						$product[$temp[0]]['quantity'] = $temp[1];
					}
					else
					{
						$product[$temp[0]]['quantity'] += $temp[1];
					}
				}
			}
			else
			{
				$message[$temp[0]][] = '不存在该产品';
			}
		}
		foreach ($product as $k =>$p)
		{
			if ($p['quantity']>$p['available_quantity'])
			{
				$message[$k][] = '可用库存不足，需要出库'.$p['quantity'].',系统剩'.$p['available_quantity'];
			}
			if ($p['quantity'] <= 0)
			{
				$message[$k][] = '出库产品不能为负数或等于0';
			}
		}
		echo json_encode($message);exit;
	}
	
	function actionOutEdit()
	{
		$this->_view['title'] = '其他出库单编辑';
		$id = $_GET['id'];
		if ($this->_context->isGET() && ! empty($id))
		{
			$other_io = Other_IO::find('other_io.id=? and type=?', $id, Q::ini('custom_flag/other_io_type/out/value'))->asArray()->getOne();
			if ($other_io)
			{
				$item = Other_IO_Item::find('other_io_item.other_io_id=?', $id)
					->joinLeft('product_basic', 'name as product_name, number as product_number', 'product_basic.id=other_io_item.product_basic_id')
					->asArray()->getAll();
				$this->_view['other_io'] = $other_io;
				$this->_view['item'] = $item;
				$user = User::getOnDutyUser();
				$this->_view['user'] = $user;
				$warehouse = Warehouse::find()->asArray()->getAll();
				$this->_view['warehouse'] = $warehouse;
			}
			else
			{
				return $this->_redirectMessage('出库单不存在或者状态有误,请检查出库单状态', '正在返回......', url('Storage::OtherIO/OutList'), FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('提交的方式有误', '正在返回......', url('Storage::OtherIO/OutList'), FAILURE);
		}
	}
	
	function actionOutEditSave()
	{
		$this->_view['title'] = '其他出库单编辑（保存）';
		if ($this->_context->isPOST())
		{
			$key_arr = array();
			$item_arr =array();
			foreach ($_POST as $key => $value)
			{
				if (substr($key,0,11) == 'product_id_')
				{
					$key_arr[] = substr($key,11,strlen($key)-11);
				}
			}
			foreach ($key_arr as $k)
			{
				$temp = array();
				$temp['product_basic_id'] = $_POST['product_id_'.$k];
				$temp['quantity'] = intval($_POST['quantity_'.$k]);
				$temp['cost_price'] = 0;
				$item_arr[$k] = $temp;
			}
			$warehouse_id = Warehouse::getDefaultWarehouseId();
			$other_io = array(
					'id' => $_POST['other_io_id'],
					'user_id' => $_POST['user_id'],
					'warehouse_id' => $_POST['warehouse_id'],
					'notes' => trim($_POST['notes']),
					'item' => $item_arr
			);
			$result = Other_IO::editOtherOut($other_io);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('保存成功', '正在返回..', url('Storage::OtherIO/OutList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('保存失败', $result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}
	
	function actionOutList()
	{
		$this->_view['title'] = '其他出库单列表';
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['type'] = Q::ini('custom_flag/other_io_type/out/value');
		$result = Other_IO::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$other_io = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::OtherIO/OutList', $url_arr));
			$this->_view['other_io'] = $other_io;
			$this->_view['page'] = $page->getPage();;
		}
	}
	
	
	/**
	 * 导入库存单
	 */
	function actionImportIn()
	{
		$this->_view['title'] = '导入创建入库单';
		$user = User::getOnDutyUser();
		$this->_view['user'] = $user;
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		
		if($this->_context->isPOST())
		{
			$upload_result = Upload_Files::uploadFile('infile', Q::ini('custom_flag/upload_file_type/product_basic/value'));
			if ($upload_result['ack'] == SUCCESS)
			{
				$item_arr = array();
				$infile = Helper_BSS_XLS::xlsFileToArray($upload_result['path'], $upload_result['file_id']);
				foreach($infile as $k => $v)
				{
					$basic = Product_Basic::find('number=?', $v['number']) -> asArray() -> getOne();
					if($basic)
					{
						$item_arr[] = array('product_basic_id' => $basic['id'],
								'quantity' => $v['inventory'],
								'cost_price' => $v['costs']
						);
					}
				}

				$other_io = array(
						'user_id' => $_POST['user_id'],
						'notes' => trim($_POST['notes']),
						'warehouse_id' => $_POST['warehouse_id'],
						'item' => $item_arr
				);
				
				$result = Other_IO::createOtherIn($other_io);
				if ($result['ack'] == SUCCESS)
				{
					
					return $this->_redirectMessage('导入成功', '正在返回..', url('Storage::OtherIO/InList'), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('导入失败', '不能生成入库单编号', url('Storage::OtherIO/InCreate'), FAILURE);
				}

			}
		}
	}
}